package examples.webstore.service;


import java.util.Calendar;
import java.util.Date;
import java.util.List;

import edu.scsu.csci.annotation.ADomainObject;
import edu.scsu.csci.annotation.AExpose;
import edu.scsu.csci.annotation.AInterceptor;
import edu.scsu.csci.annotation.AScope;
import edu.scsu.csci.annotation.AView;
import edu.scsu.csci.annotation.validator.AValidate;
import edu.scsu.csci.controller.WebUtils;
import edu.scsu.csci.core.EScope;
import examples.webstore.domainobject.Product;
import examples.webstore.interceptor.Audit;

@AExpose(expose = true, allow= {"add", "showDetails", "showAll"})
/**
 * @viz.diagram ProductService.tpx
 */
public class ProductService {

	/**
	 * Adds the product to the database.
	 * 
	 * @param product
	 */
	@ADomainObject(clazz = Product.class, scope = EScope.REQUEST)
	@AValidate(method="canAdd")
	@AInterceptor(interceptors = {Audit.class})
	@AView(resourceName = "productList", errorResourceName = "addProduct")
	@AScope(key="productList")
	public List<Product> add(Product product) {
		Product.add(product);
		return Product.displayList(product.getZipCode()); 
	}
	
	/**
	 * Validates the products price.
	 * 
	 * @param product 
	 * @return
	 */
	public boolean canAdd(Product product){
		boolean isNotAvailable = product.isNotAvailable();
		if(!isNotAvailable){
			WebUtils.setExecutionError("Product name", "A product with a similar name already exists. Please choose a different name.");
			return false;
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -5);
		Date fromDate = calendar.getTime();
		
		if(Product.getProductCountByUser(product.getSellerName(), fromDate) >= 5){
			WebUtils.setExecutionError("BuisnessLogic", "You have already added 5 products in the " +
								"last one week and can't go beyond that. Please try adding next week");
			return false;
		}
		
		return true;
	}
	 
	
	@ADomainObject(clazz = Product.class, scope = EScope.REQUEST) 
	@AView(resourceName = "productDetail", errorResourceName = "productDetail")
	public Product showDetails(Product product){
		product = Product.getProduct(product.getName());
		if(product == null){
			throw new RuntimeException("Nor product defined by this name.");
		}
		return product;
	}
	
	@AScope(key="productList")
	@AView(resourceName = "productList", errorResourceName = "productList")
	public List<Product> showAll()	{
		return Product.displayList(-1);
	}
}
